Page({
  data: {
    // 视频号列表
    videoList: [
      {
        id: 1,
        account: 'sphCRia9DylqTlc',
        feedId: 'export/UzFfAgtgekIEAQAAAAAATy4sYLw7swAAAAstQy6ubaLX4KHWvLEZgBPEqoBkYyMceJWIzNPgMJrVGvn5UlP8fJsQGA9WWMI_',
        title: '林基路精神传承 - 革命先烈的光辉足迹',
        coverImage: '../../images/封面.jpg'
      },
      {
        id: 2,
        account: 'RedCulture_Video',
        feedId: '',
        title: '走进林基路故乡台山 - 感受革命精神',
        coverImage: '../../images/封面.jpg'
      },
      {
        id: 3,
        account: 'History_Education',
        feedId: '',
        title: '重温延安岁月 - 林基路的学习生涯',
        coverImage: '../../images/封面.jpg'
      }
    ],
    
    // 添加视频相关
    showAddVideoModal: false, // 是否显示添加视频弹窗
    apiKey: '', // API密钥
    showApiKey: false, // 是否显示API密钥
    isApiKeyVerified: false, // API密钥是否已验证
    newVideoAccount: '', // 新视频号账号
    newVideoFeedId: '', // 新视频Feed ID
    newVideoTitle: '', // 新视频标题
    
    // API密钥配置（实际应用中应存储在服务端）
    validApiKey: 'LinJiLu2024RedCulture' // 有效的API密钥
  },

  onLoad(options) {
    console.log('视频代言页面加载');
    
    // 尝试从本地存储读取视频列表
    try {
      const savedVideoList = wx.getStorageSync('videoList');
      if (savedVideoList && savedVideoList.length > 0) {
        this.setData({
          videoList: savedVideoList
        });
      }
    } catch (e) {
      console.error('读取视频列表失败:', e);
    }
  },

  // 打开视频号视频
  openChannelsVideo(e) {
    const videoId = e.currentTarget.dataset.id;
    const video = this.data.videoList.find(item => item.id == videoId);
    
    if (!video) {
      wx.showToast({
        title: '视频信息不存在',
        icon: 'none'
      });
      return;
    }
    
    console.log('点击打开视频号视频:', video);
    
    // 检查是否配置了视频号信息
    if (!video.account || video.account === '') {
      wx.showModal({
        title: '提示',
        content: '视频号账号信息异常\n\n当前账号: ' + (video.account || '未配置'),
        showCancel: false
      });
      return;
    }
    
    // 显示加载提示
    wx.showLoading({
      title: '正在打开视频号...',
      mask: true
    });
    
    // 使用跳转方式打开视频号视频
    wx.openChannelsActivity({
      finderUserName: video.account,
      feedId: video.feedId || '', // 可选，不填则打开视频号主页
      success: (res) => {
        wx.hideLoading();
        console.log('打开视频号成功:', res);
        wx.showToast({
          title: '跳转成功',
          icon: 'success',
          duration: 1000
        });
      },
      fail: (err) => {
        wx.hideLoading();
        console.error('打开视频号失败:', err);
        
        let errorMsg = '打开视频号失败';
        if (err.errCode) {
          switch (err.errCode) {
            case -1:
              errorMsg = '系统错误，请稍后重试';
              break;
            case 10001:
              errorMsg = '视频号账号不存在';
              break;
            case 10002:
              errorMsg = '视频ID不存在';
              break;
            case 10003:
              errorMsg = '用户取消操作';
              break;
            default:
              errorMsg = `错误代码: ${err.errCode}`;
          }
        }
        
        wx.showModal({
          title: '打开失败',
          content: `${errorMsg}\n\n账号: ${video.account}\n视频ID: ${video.feedId || '未指定'}`,
          showCancel: false
        });
      }
    });
  },

  // 显示添加视频弹窗
  showAddVideoModal() {
    this.setData({
      showAddVideoModal: true,
      apiKey: '',
      showApiKey: false,
      isApiKeyVerified: false,
      newVideoAccount: '',
      newVideoFeedId: '',
      newVideoTitle: ''
    });
  },
  
  // 隐藏添加视频弹窗
  hideAddVideoModal() {
    this.setData({
      showAddVideoModal: false
    });
  },
  
  // 阻止冒泡
  preventBubble() {
    // 空函数，用于阻止点击事件冒泡
  },
  
  // API密钥输入处理
  onApiKeyInput(e) {
    this.setData({
      apiKey: e.detail.value
    });
  },
  
  // 切换API密钥可见性
  toggleApiKeyVisibility() {
    this.setData({
      showApiKey: !this.data.showApiKey
    });
  },
  
  // 验证API密钥
  verifyApiKey() {
    const { apiKey, validApiKey } = this.data;
    
    if (!apiKey) {
      wx.showToast({
        title: '请输入API密钥',
        icon: 'none'
      });
      return;
    }
    
    // 显示加载提示
    wx.showLoading({
      title: '验证中...',
      mask: true
    });
    
    // 模拟验证过程
    setTimeout(() => {
      wx.hideLoading();
      
      if (apiKey === validApiKey) {
        this.setData({
          isApiKeyVerified: true
        });
        
        wx.showToast({
          title: '验证成功',
          icon: 'success'
        });
      } else {
        wx.showModal({
          title: '验证失败',
          content: 'API密钥不正确，请重新输入',
          showCancel: false
        });
      }
    }, 1000);
  },
  
  // 视频号账号输入处理
  onVideoAccountInput(e) {
    this.setData({
      newVideoAccount: e.detail.value
    });
  },
  
  // 视频Feed ID输入处理
  onVideoFeedIdInput(e) {
    this.setData({
      newVideoFeedId: e.detail.value
    });
  },
  
  // 视频标题输入处理
  onVideoTitleInput(e) {
    this.setData({
      newVideoTitle: e.detail.value
    });
  },
  
  // 提交新视频
  submitNewVideo() {
    const { newVideoAccount, newVideoFeedId, newVideoTitle, videoList } = this.data;
    
    // 验证表单
    if (!newVideoAccount) {
      wx.showToast({
        title: '请输入视频号账号',
        icon: 'none'
      });
      return;
    }
    
    if (!newVideoTitle) {
      wx.showToast({
        title: '请输入视频标题',
        icon: 'none'
      });
      return;
    }
    
    // 显示加载提示
    wx.showLoading({
      title: '提交中...',
      mask: true
    });
    
    // 模拟提交过程
    setTimeout(() => {
      wx.hideLoading();
      
      // 生成新的视频ID
      const newId = Math.max(...videoList.map(v => v.id), 0) + 1;
      
      // 创建新视频对象
      const newVideo = {
        id: newId,
        account: newVideoAccount,
        feedId: newVideoFeedId || '',
        title: newVideoTitle,
        coverImage: '../../images/封面.jpg' // 默认封面，实际应用中可以让用户上传
      };
      
      // 添加到视频列表
      const updatedVideoList = [...videoList, newVideo];
      
      this.setData({
        videoList: updatedVideoList,
        showAddVideoModal: false
      });
      
      // 保存到本地存储（实际应用中应保存到服务端数据库）
      try {
        wx.setStorageSync('videoList', updatedVideoList);
      } catch (e) {
        console.error('保存视频列表失败:', e);
      }
      
      wx.showToast({
        title: '添加成功',
        icon: 'success',
        duration: 2000
      });
    }, 1500);
  },
  
  // 删除视频
  deleteVideo(e) {
    const videoId = e.currentTarget.dataset.id;
    const video = this.data.videoList.find(item => item.id == videoId);
    
    if (!video) {
      wx.showToast({
        title: '视频不存在',
        icon: 'none'
      });
      return;
    }
    
    wx.showModal({
      title: '确认删除',
      content: `确定要删除视频"${video.title}"吗？`,
      confirmText: '删除',
      confirmColor: '#ff4444',
      success: (res) => {
        if (res.confirm) {
          const updatedVideoList = this.data.videoList.filter(item => item.id != videoId);
          
          this.setData({
            videoList: updatedVideoList
          });
          
          // 保存到本地存储
          try {
            wx.setStorageSync('videoList', updatedVideoList);
          } catch (e) {
            console.error('保存视频列表失败:', e);
          }
          
          wx.showToast({
            title: '删除成功',
            icon: 'success'
          });
        }
      }
    });
  },
  
  // 分享功能
  onShareAppMessage() {
    return {
      title: '林基路精神传承 - 视频代言',
      path: '/pages/video/index',
      imageUrl: '../../images/avatar.png'
    };
  }
}); 